<template>
    <div class="invoice-register"  style="height: 800px;">
      <!-- 顶部查询区域 -->
      <el-form :model="searchForm" inline class="search-form" label-width="80px">
        <!-- 单据日期范围 -->
        <el-form-item label="单据日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :default-value="[new Date('2025-06-01'), new Date('2025-06-24')]"
          />
        </el-form-item>
  
        <!-- 单据编号（多号用,分隔） -->
        <el-form-item label="单据编号">
          <el-input
            v-model="searchForm.docNos"
            placeholder="多个单号用,隔开"
            clearable
          />
        </el-form-item>
  
        <!-- 供应商选择（支持远程搜索） -->
        <el-form-item label="客户">
          <el-select
            v-model="searchForm.supplier"
            placeholder="请选择客户"
            clearable
            remote
            :remote-method="searchSupplier"
            loading-text="搜索中..."
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
  
        <!-- 业务员选择（支持远程搜索） -->
        <el-form-item label="销售人员">
          <el-select
            v-model="searchForm.salesman"
            placeholder="请选择销售人员"
            clearable
            remote
            :remote-method="searchSalesman"
            loading-text="搜索中..."
          >
            <el-option
              v-for="item in salesmanOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
  
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
  
        <!-- 展开条件（下拉菜单） -->
        <el-form-item>
          <el-dropdown trigger="click">
            <el-button type="text" icon="el-icon-arrow-down">展开条件</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="toggleColumnSetting"
                  >列设置</el-dropdown-item
                >
                <el-dropdown-item>高级筛选</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

        <el-form-item>
          <el-dropdown trigger="click">
            <el-button type="text" icon="el-icon-arrow-down">操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item  type="primary" @click="handleRegister"
                  >发票登记</el-dropdown-item
                >
                <el-dropdown-item @click="handleInvoiceRecord"
                  >开票记录</el-dropdown-item
                >
                <el-dropdown-item @click="handleExport"
                  >导出</el-dropdown-item
                >
             
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

      </el-form>
  
      <!-- 表格区域（带合计行） -->
      <div class="table-container">
        <el-table
          ref="table"
          :data="tableData"
          border
          show-summary
          :summary-method="calcSummary"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#F8F9FA' }"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="docDate" label="单据日期" width="120" />
          <el-table-column prop="docNo" label="单据编号" width="150" />
          <el-table-column
            prop="relatedOrder"
            label="关联购货订单号"
            width="180"
          />
          <el-table-column prop="supplier" label="供应商" width="180" />
          <el-table-column prop="creator" label="源制单人" width="120" />
          <el-table-column prop="qty" label="数量" width="100" align="right" />
          <el-table-column prop="amount" label="金额" width="120" align="right" />
          <el-table-column
            prop="taxAmount"
            label="税额"
            width="120"
            align="right"
          />
          <el-table-column
            prop="paidAmount"
            label="已付款"
            width="120"
            align="right"
          />
          <el-table-column prop="payStatus" label="付款状态" width="120">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.payStatus === '已付'
                    ? 'success'
                    : scope.row.payStatus === '部分付'
                    ? 'warning'
                    : 'info'
                "
              >
                {{ scope.row.payStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="totalAmount"
            label="价税合计"
            width="120"
            align="right"
          />
          <el-table-column
            prop="invoicedAmount"
            label="已开票金额"
            width="120"
            align="right"
          />
        </el-table>
      </div>
  
      <!-- 发票登记表单 - 使用栅格系统布局在一行 -->
      <el-form
        ref="invoiceForm"
        :model="invoiceForm"
        :rules="invoiceRules"
        label-width="100px"
        class="invoice-form"
      >
        <el-row :gutter="16">
          <el-col :span="4">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="invoiceForm.invoiceDate"
                type="date"
                value-format="YYYY-MM-DD"
                :default-value="new Date('2025-06-24')"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item label="*发票号" prop="invoiceNo">
              <el-input
                v-model="invoiceForm.invoiceNo"
                placeholder="请输入12位发票号"
                max-length="12"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input
                v-model.number="invoiceForm.invoiceAmount"
                placeholder="自动计算（价税合计总和）"
                readonly
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item label="销售方" prop="seller">
              <el-input v-model="invoiceForm.seller" placeholder="请输入销售方名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item label="*发票抬头" prop="invoiceTitle">
              <el-input
                v-model="invoiceForm.invoiceTitle"
                placeholder="默认：云进销存体验账套"
                :default-value="invoiceForm.invoiceTitle"
              />
            </el-form-item>
          </el-col>
          
         
        </el-row>
        
        <!-- 备注信息保留在单独一行 -->
        <el-form-item label="开票备注" prop="remark">
          <el-input
            v-model="invoiceForm.remark"
            type="textarea"
            placeholder="填写发票特殊说明"
            rows="3"
          />
        </el-form-item>
      </el-form>
  
      <!-- 列设置弹窗（示例） -->
      <el-dialog title="列设置" v-model="columnDialogVisible" width="400px">
        <el-checkbox-group v-model="visibleColumns">
          <el-checkbox label="docDate">单据日期</el-checkbox>
          <el-checkbox label="docNo">单据编号</el-checkbox>
          <el-checkbox label="relatedOrder">关联订单号</el-checkbox>
          <!-- 更多列... -->
        </el-checkbox-group>
        <template #footer>
          <el-button @click="columnDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveColumnSetting">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: "PurchaseInvoiceRegister",
    data() {
      return {
        // 查询条件
        searchForm: {
          dateRange: ["2025-06-01", "2025-06-24"],
          docNos: "",
          supplier: "",
          salesman: "",
        },
        // 供应商/业务员下拉选项（模拟远程搜索）
        supplierOptions: [],
        salesmanOptions: [],
        // 表格数据（5条完整数据）
        tableData: [
          {
            docDate: "2025-06-10",
            docNo: "PO20250610001",
            relatedOrder: "ORD20250601",
            supplier: "杭州示例供应商A",
            creator: "张三",
            qty: 100,
            amount: 10000,
            taxAmount: 1300,
            paidAmount: 5000,
            payStatus: "部分付",
            totalAmount: 11300,
            invoicedAmount: 0,
          },
          {
            docDate: "2025-06-12",
            docNo: "PO20250612002",
            relatedOrder: "ORD20250603",
            supplier: "上海示例供应商B",
            creator: "李四",
            qty: 200,
            amount: 20000,
            taxAmount: 2600,
            paidAmount: 20000,
            payStatus: "已付",
            totalAmount: 22600,
            invoicedAmount: 0,
          },
          {
            docDate: "2025-06-15",
            docNo: "PO20250615003",
            relatedOrder: "ORD20250605",
            supplier: "广州示例供应商C",
            creator: "王五",
            qty: 150,
            amount: 15000,
            taxAmount: 1950,
            paidAmount: 0,
            payStatus: "未付",
            totalAmount: 16950,
            invoicedAmount: 0,
          },
          {
            docDate: "2025-06-18",
            docNo: "PO20250618004",
            relatedOrder: "ORD20250607",
            supplier: "深圳示例供应商D",
            creator: "赵六",
            qty: 50,
            amount: 5000,
            taxAmount: 650,
            paidAmount: 5000,
            payStatus: "已付",
            totalAmount: 5650,
            invoicedAmount: 0,
          },
          {
            docDate: "2025-06-20",
            docNo: "PO20250620005",
            relatedOrder: "ORD20250609",
            supplier: "北京示例供应商E",
            creator: "孙七",
            qty: 300,
            amount: 30000,
            taxAmount: 3900,
            paidAmount: 15000,
            payStatus: "部分付",
            totalAmount: 33900,
            invoicedAmount: 0,
          },
        ],
        // 选中的单据（用于计算发票金额）
        selectedRows: [],
        // 发票登记表单
        invoiceForm: {
          invoiceDate: "2025-06-24",
          invoiceNo: "",
          invoiceAmount: 0,
          seller: "",
          invoiceTitle: "云进销存体验账套",
          remark: "",
        },
        // 表单验证规则
        invoiceRules: {
          invoiceNo: [
            { required: true, message: "请输入发票号", trigger: "blur" },
            {
              pattern: /^\d{12}$/,
              message: "发票号必须为12位数字",
              trigger: "blur",
            },
          ],
          invoiceTitle: [
            { required: true, message: "请输入发票抬头", trigger: "blur" },
          ],
        },
        // 列设置弹窗
        columnDialogVisible: false,
        visibleColumns: ["docDate", "docNo", "relatedOrder"], // 默认显示列
      };
    },
    methods: {
      // 模拟远程搜索供应商
      searchSupplier(keyword) {
        // 实际调用接口：this.supplierOptions = await api.searchSupplier(keyword)
        this.supplierOptions = [
          { label: `供应商A-${keyword}`, value: `supplierA-${keyword}` },
          { label: `供应商B-${keyword}`, value: `supplierB-${keyword}` },
        ];
      },
      // 模拟远程搜索业务员
      searchSalesman(keyword) {
        // 实际调用接口：this.salesmanOptions = await api.searchSalesman(keyword)
        this.salesmanOptions = [
          { label: `业务员1-${keyword}`, value: `sales1-${keyword}` },
          { label: `业务员2-${keyword}`, value: `sales2-${keyword}` },
        ];
      },
      // 查询单据（模拟接口）
      handleQuery() {
        // 实际逻辑：调用接口获取tableData
        this.$message.success("查询成功！");
      },
      // 表格合计计算
      calcSummary({ columns, data }) {
        const sums = [];
        columns.forEach((col, index) => {
          if (index === 0) {
            sums[index] = "合计:";
            return;
          }
          const prop = col.prop;
          if (
            [
              "qty",
              "amount",
              "taxAmount",
              "paidAmount",
              "totalAmount",
              "invoicedAmount",
            ].includes(prop)
          ) {
            sums[index] = data.reduce((acc, cur) => acc + (cur[prop] || 0), 0);
          } else {
            sums[index] = "";
          }
        });
        return sums;
      },
      // 选中行变化（计算发票金额）
      handleSelectionChange(val) {
        this.selectedRows = val;
        this.invoiceForm.invoiceAmount = val.reduce(
          (acc, cur) => acc + cur.totalAmount,
          0
        );
      },
      // 发票登记（核心逻辑）
      handleRegister() {
        this.$refs.invoiceForm.validate((valid) => {
          if (valid) {
            if (this.selectedRows.length === 0) {
              this.$message.warning("请选择需要开票的采购单据！");
              return;
            }
            // 模拟登记：调用接口保存发票信息 + 更新单据已开票金额
            this.$message.success(
              `发票登记成功！发票号：${this.invoiceForm.invoiceNo}`
            );
            // 清空表单
            this.invoiceForm = {
              invoiceDate: "2025-06-24",
              invoiceNo: "",
              invoiceAmount: 0,
              seller: "",
              invoiceTitle: "云进销存体验账套",
              remark: "",
            };
            // 清空表格选中
            this.$refs.table.clearSelection();
          }
        });
      },
      // 查看开票记录（示例）
      handleInvoiceRecord() {
        this.$message.info("开票记录功能待实现");
      },
      // 导出数据（示例）
      handleExport() {
        this.$message.info("导出功能待实现");
      },
      // 打开列设置弹窗
      toggleColumnSetting() {
        this.columnDialogVisible = true;
      },
      // 保存列设置（示例）
      saveColumnSetting() {
        this.$message.success("列设置已保存！");
        this.columnDialogVisible = false;
      },
    },
  };
  </script>
  
  <style scoped>
  .invoice-register {
    padding: 24px;
    background: #fff;
  }
  
  .search-form {
    margin-bottom: 16px;
  }
  
  .table-container {
    margin: 20px 0;
  }
  
  .invoice-form {
    margin-top: 24px;
  }
  
  .el-table {
    width: 100%;
  }
  
  .el-tag {
    padding: 2px 8px;
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  </style>    